package com.xyh.transaction.listener;

import com.xyh.transaction.common.Constant;
import com.xyh.transaction.common.ImageType;
import com.xyh.transaction.entity.Category;
import com.xyh.transaction.entity.Goods;
import com.xyh.transaction.entity.User;
import com.xyh.transaction.entity.vo.BaseCategoryVo;
import com.xyh.transaction.entity.vo.GoodsVo;
import com.xyh.transaction.entity.vo.ImageVo;
import com.xyh.transaction.entity.vo.UserVo;
import com.xyh.transaction.mapper.ImageMapper;
import com.xyh.transaction.utils.ImageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class MapImageEventListener {

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private ImageUtils imageUtils;

    @EventListener
    public void mappingGoodsImage(MapGoodsImageEvent event) {
        Goods goods = event.getGoods();
        GoodsVo goodsVo = event.getGoodsVo();

        List<ImageVo> imageVoList = imageMapper.findByRelatedId(goods.getId(), ImageType.GOODS).stream()
                .map(image -> new ImageVo(image.getAltText(), imageUtils.buildImageUrl(image.getUrl())))
                .collect(Collectors.toList());
        // 封面图
        if (imageVoList.isEmpty()) {
            imageVoList.add(new ImageVo("默认商品图", imageUtils.buildImageUrl(Constant.DEFAULT_GOODS)));
        }
        goodsVo.setPicture(imageVoList.get(0).getUrl());
        goodsVo.setPictures(imageVoList);
    }

    @EventListener
    public void mappingCategoryImage(MapCategoryImageEvent event) {
        Category category = event.getCategory();
        BaseCategoryVo categoryVo = event.getCategoryVo();

        List<String> imageUrls = imageMapper.findByRelatedId(category.getId(),ImageType.CATEGORY).stream()
                .map(image -> imageUtils.buildImageUrl(image.getUrl())).collect(Collectors.toList());

        if (imageUrls.isEmpty()) {
            imageUrls.add(imageUtils.buildImageUrl(Constant.DEFAULT_CATEGORY));
        }

        categoryVo.setPicture(imageUrls.get(0));
    }

    @EventListener
    private void mappingAvatarImage(MapAvatarImageEvent event) {
        User user = event.getUser();
        UserVo userVo = event.getUserVo();

        List<String> imageUrls = imageMapper.findByRelatedId(user.getId(),ImageType.AVATAR).stream()
                .map(image -> imageUtils.buildImageUrl(image.getUrl())).collect(Collectors.toList());

        if (imageUrls.isEmpty()) {
            imageUrls.add(imageUtils.buildImageUrl(Constant.DEFAULT_AVATAR));
        }

        userVo.setAvatar(imageUrls.get(0));

    }


}
